package com.lcy.web.shiro

import com.lcy.web.dao.mapper.UserMapper
import org.apache.shiro.authc.*
import org.apache.shiro.authz.AuthorizationInfo
import org.apache.shiro.authz.SimpleAuthorizationInfo
import org.apache.shiro.cache.MemoryConstrainedCacheManager
import org.apache.shiro.realm.AuthorizingRealm
import org.apache.shiro.subject.PrincipalCollection
import org.springframework.beans.factory.annotation.Autowired

/**
 * @author loucy
 */
class UserRealm : AuthorizingRealm() {
    @Autowired
    lateinit var userMapper:UserMapper
    init {
        cacheManager = MemoryConstrainedCacheManager()
    }
    override fun doGetAuthenticationInfo(token: AuthenticationToken): AuthenticationInfo {
        val myToken = token as UsernamePasswordToken
        val user = userMapper.getUserRolesByName(myToken.username)
        if (user != null){
            return SimpleAuthenticationInfo(user.name,user.password,name)
        }else{
            throw AuthenticationException()
        }
    }

    override fun doGetAuthorizationInfo(principals: PrincipalCollection): AuthorizationInfo {
        val userName = principals.primaryPrincipal as String
        val user = userMapper.getUserRolesByName(userName)
        val roleNames = userMapper.getRoleNames(user?.roleIds)
        val info = SimpleAuthorizationInfo()
        if(roleNames != null) {
            info.addRoles(roleNames)
        }
        return info
    }

}

